
package com.jxccp.ui.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.utils.JXPermissionUtil;

import java.util.List;

public class JXWebViewActivity extends JXBaseActivity implements OnClickListener,
        JXPermissionUtil.OnPermissionCallback {


    private LinearLayout rootView;

    private WebView webView;

    private ProgressBar web_pb;

    private ImageView backView;

    private String url;

    private TextView titleText;

    private boolean isAmap = false;

    private boolean isLocation = false;

    private JXPermissionUtil mJXPermissionUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jx_activity_leave_msg);

        rootView = (LinearLayout) findViewById(R.id.ll_container);
        web_pb = (ProgressBar) findViewById(R.id.web_pb);
        backView = (ImageView) findViewById(R.id.iv_left);
        titleText = findViewById(R.id.tv_actionTitle);
        titleText.setVisibility(View.GONE);
        backView.setOnClickListener(this);

        if (JXUiHelper.getInstance().getmTitleBgColorId() != JXUiHelper.INVALID_INT) {
            findViewById(R.id.rl_root).setBackgroundColor(getResources().getColor(JXUiHelper
                    .getInstance().getmTitleBgColorId()));
        }

        if (JXUiHelper.getInstance().getmTitleTextColorResId() != JXUiHelper.INVALID_INT) {
            ((TextView) findViewById(R.id.tv_actionTitle)).setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
        }

        if (JXUiHelper.getInstance().getmTitleLeftImgResId() != JXUiHelper.INVALID_INT) {
            ((ImageView) findViewById(R.id.iv_left)).setImageResource(JXUiHelper.getInstance()
                    .getmTitleLeftImgResId());
        }

        url = getIntent().getStringExtra(JXConstants.EXTRA_WEBVIEW_URL);
        isAmap = getIntent().getBooleanExtra(JXConstants.EXTRA_AMAP_URL, false);
        isLocation = getIntent().getBooleanExtra(JXConstants.EXTRA_GET_LOCATION, false);

        JXLog.d("[JXWebViewActivity.oncreate] open url = " + url);
        if (TextUtils.isEmpty(url)) {
            finish();
        } else {
            if (isAmap && url.contains("navigation") && !url.contains("from")) {
                //导航没有起始点，先请求位置权限
                mJXPermissionUtil = new JXPermissionUtil();
                int permissRequestCode = 1;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    String[] permissions = new String[]{Manifest.permission
                            .ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
                    mJXPermissionUtil.requestPermissions(this, permissRequestCode, permissions,
                            JXWebViewActivity.this);
                } else {
                    init(url);
                }
            }else if(isLocation){
                mJXPermissionUtil = new JXPermissionUtil();
                int permissRequestCode = 1;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    String[] permissions = new String[]{Manifest.permission
                            .ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
                    mJXPermissionUtil.requestPermissions(this, permissRequestCode, permissions,
                            JXWebViewActivity.this);
                }else {
                    init(url);
                }
            } else {
                init(url);
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init(String address) {
        webView = (WebView) findViewById(R.id.webView);
        // 启用支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 优先使用缓存
//        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        webView.getSettings().setLoadWithOverviewMode(true);

        webView.getSettings().setDomStorageEnabled(true);

        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webView.getSettings().setGeolocationDatabasePath(dir);

        webView.getSettings().setGeolocationEnabled(true);

        webView.addJavascriptInterface(new Amap(), "amap");//Amap类对象映射到js的test对象

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }

        // WebView加载web资源
        webView.loadUrl(address);

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                JXLog.e("[JXWebViewActivity.shouldOverrideUrlLoading] overrideurl = " + url);
                try {
                    if (!url.startsWith("http") && !url.startsWith("https")) {
                        if (isAmap && appIsInstalled(JXWebViewActivity.this, "com.autonavi" +
                                ".minimap")) {
                            showAmapAlert(url);
                        }
                        return true;
                    }
                } catch (Exception e) {
                    JXLog.e("[JXWebViewActivity.shouldOverrideUrlLoading] over ride exception", e);
                    return true;
                }
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String title = view.getTitle();
                JXLog.d("[JXWebViewActivity.onPageFinished] title ="+title);
                if (!TextUtils.isEmpty(title)) {
                    titleText.setVisibility(View.VISIBLE);
                    titleText.setText(title);
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    web_pb.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == web_pb.getVisibility()) {
                        web_pb.setVisibility(View.VISIBLE);
                    }
                    web_pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onCloseWindow(WebView window) {
                JXLog.d("[JXWebViewActivity.shouldOverrideUrlLoading] on close window event");
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        JXWebViewActivity.this.finish();
                    }
                }, 500);
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

                builder.setMessage(message)
                        .setPositiveButton(getString(R.string.jx_confirm), null);
                // 禁止响应按back键的事件
                builder.setCancelable(false);
                AlertDialog dialog = builder.create();
                dialog.show();
                result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
                return true;
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions
                    .Callback callback) {
                JXLog.d("[JXWebViewActivity.setWebChromeClient] onGeolocationPermissionsShowPrompt");
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_left) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //webView资源释放
        if (rootView != null) {
            rootView.removeAllViews();
        }
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
        }
    }

    /**
     * 打开高德地图弹窗
     * @param url
     */
    public void showAmapAlert(final String url) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app
                .AlertDialog.Builder(JXWebViewActivity.this);
        builder.setMessage("是否打开高德地图？");
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int what) {
                dialogInterface.dismiss();
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int what) {
                dialogInterface.dismiss();
            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    /**
     * 是否安装高德
     * @param context
     * @param packageName
     * @return
     */
    public boolean appIsInstalled(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            List<PackageInfo> packageInfoList = manager.getInstalledPackages(0);
            if (packageInfoList != null) {
                for (int i = 0; i < packageInfoList.size(); i++) {
                    String package_name = packageInfoList.get(i).packageName;
                    if (package_name.equals(packageName)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            JXLog.e("[JXWebViewActivity.appIsInstalled] check app installed exception", e);
            return false;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mJXPermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        init(url);
    }

    @Override
    public void onDenied() {
        init(url);
    }


    /**
     * 发送位置
     */
    public class Amap extends Object {

        // 定义JS需要调用的方法
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public void sendLoaction(String lat,String log, String lable) {
            JXLog.d("[JXWebViewActivity.sendLoaction] JS调用了Android的send loaction 方法,lat = "+lat + " , log = "+log+" , lable = "+lable);
            Intent intent = new Intent();
            intent.putExtra("lat", lat);
            intent.putExtra("log", log);
            intent.putExtra("lable", lable);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
